package com.rookie.shiro.module.config.security;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.rookie.shiro.module.constant.ErrorEnum;
import com.rookie.shiro.module.constant.SecurityConstant;
import com.rookie.shiro.module.constant.TokenTypeEnum;
import com.rookie.shiro.module.util.JwtUtils;
import com.rookie.shiro.module.util.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author rookie
 */

@Component
public class AdminShiroSecurity implements ShiroSecurity{

   /* @Resource
  @Lazy
    private ISysPermService permService;*/

   /* @Autowired
   @Lazy
    private RedisUtils redisUtils;*/

    @Override
    public boolean supports(String token) throws AuthenticationException {
        if (StringUtils.isBlank(token)){
            return false;
        }
        String claim = null;
        try {
            claim = JwtUtils.getClaim(token, SecurityConstant.TOKEN_TYPE_NAME);
        } catch (Exception e) {
            throw new CredentialsException(ErrorEnum.E_30004.getErrorMsg());
        }
        return TokenTypeEnum.ADMIN.getMessage().equals(claim);
    }

    @Override
    public List<String> getUserPermission(String token) {
        List<String> permList = new ArrayList<>();
        if (StringUtils.isBlank(token)){
            return permList;
        }
        Integer userRoleId = TokenUtils.getUserRoleId();
        return permList;
//        return permService.listUserPermission(userRoleId);
    }

    @Override
    public void doGetAuthentication(String token) throws AuthenticationException {
        try {
            JwtUtils.verify(token);
 /*           String userName = TokenUtils.getUserName(token);
//            验证是否在redis中
            if (!redisUtils.hasKey(String.format(CommonConstant.REDIS_USER_LOGIN,userName))){
                throw new ExpiredCredentialsException(ErrorEnum.E_30001.getErrorMsg());
            }*/
        } catch (TokenExpiredException e) {
            throw new ExpiredCredentialsException(ErrorEnum.E_30001.getErrorMsg());
        }catch (Exception e){
            throw new CredentialsException(ErrorEnum.E_30004.getErrorMsg());
        }
    }

}
